﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace OOAD_Project_Engine.Application.Services
{
    public class GraphicService : GameComponent, IGraphicService
    {
        GraphicsDevice graphicsDevice;
        SpriteBatch spriteBatch;

        public GraphicService(Game game)
            : base(game)
        {
            Game.Components.ComponentAdded += this.OnComponentAdded;
            Game.Components.ComponentRemoved += this.OnComponentRemoved;
        }

        public override void Initialize()
        {
            base.Initialize();
            graphicsDevice = Game.GraphicsDevice;
            spriteBatch = new SpriteBatch(graphicsDevice);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.Game.Services.GetService(typeof(IGraphicService)) == this)
                {
                    this.Game.Services.RemoveService(typeof(IGraphicService));
                }
            }

            base.Dispose(disposing);
        }

        public GraphicsDevice GraphicsDevice
        {
            get { return graphicsDevice; }
        }

        public SpriteBatch SpriteBatch
        {
            get { return spriteBatch; }
        }

        public void OnComponentAdded(object sender, GameComponentCollectionEventArgs e)
        {
            if (e.GameComponent == this)
            {
                if (Game.Services.GetService(typeof(IGraphicService)) != null)
                {
                    throw new ArgumentException("GraphicService already present.");
                }
                Game.Services.AddService(typeof(IGraphicService), this);
            }
        }

        public void OnComponentRemoved(object sender, GameComponentCollectionEventArgs e)
        {
            if (e.GameComponent == this)
            {
                Game.Services.RemoveService(typeof(IGraphicService));
                Game.Components.ComponentAdded -= this.OnComponentAdded;
                Game.Components.ComponentRemoved -= this.OnComponentRemoved;
            }
        }
    }
}
